<template>
  <div style="text-align:left">
    <el-upload auto-upload ref="uploader"  list-type="picture-card"  
    :http-request="handleUpload" :on-preview="handlePictureCardPreview" 
    :on-remove="handleRemove" action="http://hello" :file-list="initList"
    :on-change="listenFileChange">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {client} from '../cos'
import {DEFAULT_BUCKET}  from '../cos'
import {DEFAULT_REGION}  from '../cos'
export default {
  name : "GoodsImsageList",
  //props : ["initList"],
  data(){
    return {
      dialogImageUrl : "",
      dialogVisible : false,
      initList:[],
    }
  },
  methods : {
    handleUpload(option){
      //console.log(option.file)
      console.log(client)
      let self = this;
      let file = option.file
      let name = file.name
      client.putObject({
        Bucket:DEFAULT_BUCKET,
        Region: DEFAULT_REGION,
        Key: name,
        Body: file
      },(err,data) => {
        if(err == null){
          client.getObjectUrl({
            Bucket:DEFAULT_BUCKET,
            Region: DEFAULT_REGION,
            Sign: false,
            Key: name
          },function(err,data){
            if (err == null){
              self.$message("文件上传成功")
              // TODO to set the url 
              self.initList.append({name:"",url:""})
              self.$emit("change",self.initList)
            }else{
              self.$message("文件上传失败请稍后上传")
            }
          })
        }else{
          self.$message("文件上传失败请稍后上传")
          //self.$refs.uploader.clearFiles()
          //https://blog.csdn.net/qq_27626333/article/details/81463139
        }
      })
    },
    listenFileChange(file, fileList){
      
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
        let indexArr = fileList.map((item) => item.uid)
        let index = indexArr.indexOf(file.uid)
        this.initList.remove(index)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
}
</script>

<style>

</style>
